package com.yan.ems.service;

import com.yan.ems.mapper.UserMapper;
import com.yan.ems.pojo.entity.User;
import com.yan.ems.pojo.param.UserParam;
import com.yan.ems.pojo.vo.LoginVo;
import com.yan.ems.pojo.vo.Result;
import com.yan.ems.utils.TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	public Result<LoginVo> login(UserParam userParam) {
		User user = userMapper.getUserByUsername(userParam.getUsername());
		if (user == null || !user.getPassword().equals(userParam.getPassword())) {
			return Result.error();
		}

		LoginVo loginVo = new LoginVo();
		loginVo.setUsername(user.getUsername());
		loginVo.setToken(TokenGenerator.generateToken(user.getUsername()));
		return Result.success(loginVo);
	}

	public Result<Void> register(UserParam userParam) {
		System.out.println("register");
		if (userMapper.getUserByUsername(userParam.getUsername()) != null) {
			throw new RuntimeException("用户名已存在");
		}

		User user = new User();
		user.setUsername(userParam.getUsername());
		user.setPassword(userParam.getPassword());
		user.setId(userMapper.getCount() + 1000000000);

		userMapper.addUser(user);
		return Result.success(null);
	}
}
